import React from 'react';
import { getCompanyTree, getDepartmentTree } from '@/services/components/userform';
import { translateTreeData } from '@/utils/utils';

const DICTIONARY = {
    company: {
        fileName: {
            value: 'organizationCode',
            title: 'organizationName'
        },
        xhrMethod: getCompanyTree
    },
    department: {
        fileName: {
            value: 'organizationCode',
            title: 'organizationName'
        },
        xhrMethod: getDepartmentTree
    }
};

/*
 * @param type<string> 类型
 * @param params<any> 请求参数
 * */
const useTreeSelectData = (type, params) => {
    const [data, setData] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const fetchData = async argument => {
        setLoading(true);
        const { data: rowData = [], code } = (await DICTIONARY[type].xhrMethod(argument)) || {};
        if (code === 10000) {
            const finalData = translateTreeData(rowData, DICTIONARY[type].fileName);
            setData(finalData);
        }
        setLoading(false);
    };

    React.useEffect(() => {
        console.log(params);
        fetchData(params);
    }, []);

    return [data, loading];
};

export default useTreeSelectData;
